package com.coder4j.platform.controller;

import com.coder4j.starter.generator.mapper.GeneratorMapper;
import com.coder4j.starter.generator.service.GeneratorService;
import com.coder4j.starter.generator.service.WebGeneratorService;
import com.coder4j.starter.generator.vo.CodeContentVO;
import com.coder4j.starter.generator.vo.ColumnInfo;
import com.coder4j.starter.generator.vo.TemplateVO;
import com.coder4j.starter.mybatis.BaseEntityEnums;
import com.coder4j.starter.tools.util.StringUtils;
import com.coder4j.starter.tools.util.ZipUtil;
import com.coder4j.starter.tools.vo.R;
import com.coder4j.starter.web.api.ApiNote;
import lombok.extern.slf4j.Slf4j;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import org.springframework.core.io.InputStreamResource;
import org.springframework.http.HttpHeaders;
import org.springframework.http.MediaType;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

import java.io.*;
import java.nio.file.*;
import java.util.zip.ZipOutputStream;

/**
 * 代码生成器
 * @author keller
 * @date 2025-05-25 15:34:19
 */
@RestController
@Slf4j
@RequestMapping("/codeGenerator")
public class CodeGeneratorController {

    @Resource
    private WebGeneratorService service;

    @Resource
    private GeneratorMapper mapper;

    @Resource
    private HttpServletResponse response;

    @ApiNote(name = "获取所有数据表名称",createName = "keller" ,createTime = "2025-05-25 16:45:25")
    @GetMapping("/getAllTables")
    public R getAllTable(){
        return R.success(mapper.queryAllTables());
    }

    @ApiNote(name = "获取所有表中的字段列表",createName = "keller" ,createTime = "2025-05-25 16:45:25")
    @GetMapping("/getColumnList")
    public R getColumnList(String tableName){
        if(StringUtils.isEmpty(tableName)){
            return R.paramError();
        }
        return R.success(service.initTemplate(tableName));
    }

    @ApiNote(name = "生成代码",createName = "keller" ,createTime = "2025-05-26 15:47:32")
    @PostMapping("/generator")
    public R generator(@RequestBody TemplateVO vo){
        CodeContentVO code = service.generatorTempCode(vo);
        return R.success(code);
    }

    @ApiNote(name = "下载代码",createName = "keller" ,createTime = "2025-05-26 19:43:18")
    @GetMapping("/downloadZip")
    public void downloadFolderAsZip(String tempPath) throws IOException {
        if(StringUtils.isEmpty(tempPath)){
            return;
        }
        // 源目录和目标 ZIP 文件
        String sourceDir = service.tempCodePath + File.separator + tempPath;
        Path tempZip = Files.createTempFile("tempPath", ".zip");

        // 打包目录为 ZIP
        ZipUtil.zipDirectory(sourceDir, tempZip.toString());

        // 设置响应头
        response.setContentType(MediaType.APPLICATION_OCTET_STREAM_VALUE);
        response.setHeader(HttpHeaders.CONTENT_DISPOSITION, "attachment;filename=" + tempPath + ".zip");

        // 使用 ServletOutputStream 输出二进制流
        try (InputStream inputStream = new FileInputStream(tempZip.toFile());
             OutputStream outputStream = response.getOutputStream()) {

            byte[] buffer = new byte[1024];
            int bytesRead;
            while ((bytesRead = inputStream.read(buffer)) != -1) {
                outputStream.write(buffer, 0, bytesRead);
            }
            outputStream.flush();
        }

        // 删除临时文件（可选）
        Files.deleteIfExists(tempZip);
    }


}
